/**
 * @Author: Sagan
 * @Date: 2020/09/29 23:50
 */
package module

import (
	"encoding/json"
	"gitee.com/big_meteor/godash/lang"
	"gitee.com/big_meteor/godash/validate/constant"
	"reflect"
	"strings"
)

func hasPrefixAndSuffix(str, prefix, suffix string) bool {
	return strings.HasPrefix(str, prefix) && strings.HasSuffix(str, suffix)
}

func Json(v interface{}) (bool, error) {
	var kind reflect.Kind
	v, kind = lang.GetValue(v)

	if reflect.String != kind {
		return false, constant.ERROR_JSON_UDT
	}

	return json.Valid(lang.StringToByte(v.(string))), nil
}

func JsonObject(v interface{}) (bool, error) {
	var kind reflect.Kind
	v, kind = lang.GetValue(v)

	if reflect.String != kind {
		return false, constant.ERROR_JSON_UDT
	}

	if false == hasPrefixAndSuffix(v.(string), "{", "}") {
		return false, nil
	}

	return json.Valid(lang.StringToByte(v.(string))), nil
}

func JsonArray(v interface{}) (bool, error) {
	var kind reflect.Kind
	v, kind = lang.GetValue(v)

	if reflect.String != kind {
		return false, constant.ERROR_JSON_UDT
	}

	if false == hasPrefixAndSuffix(v.(string), "[", "]") {
		return false, nil
	}

	return json.Valid(lang.StringToByte(v.(string))), nil
}
